package cn.zbmao.web.util;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: huangzheng
 * Date: 2014/11/7
 * Time: 9:45
 * To change this template use File | Settings | File Templates.
 */
public class FileUtil {

    private static final Logger LOGGER = Logger.getLogger(FileUtil.class);

    /**
     * 删除文件
     * @param path
     * @return
     */
    public static boolean delectDic(String path){
        File file ;
        file = new File(path);
        if (file.isDirectory()) {
            try {
                FileUtils.deleteDirectory(file);
                LOGGER.info("delete directory true,path:"+path);
            } catch (IOException e) {
                LOGGER.error("delete directory false,path:"+path,e);
                return false;
            }
        }else if(file.isFile()){
            try {
                FileUtils.deleteQuietly(file);
                LOGGER.info("delete file true,path:"+path);
            }catch (Exception e){
                LOGGER.error("delete file false,path:"+path,e);
                return false;
            }

        }
        return true;
    }

    /**
     * 添加文件
     * @param list
     * @param path
     * @return
     */
    public static boolean addTerms(List<String> list,String path){
       return addTerms(list, path, "utf-8");
    }

    /**
     * 添加文件
     * @param list
     * @param path
     * @param encoding
     * @return
     */
    public static boolean addTerms(List<String> list,String path,String encoding){
        boolean flag = false;
        File file = new File(path);
        if (list.size()>0){
            try {
                FileUtils.writeLines(file, encoding, list);
                flag = true;
            } catch (IOException e) {
                LOGGER.error("delete",e);
            }
        }
        return flag;
    }

    /**向文件中一行行追加记录*/
    public static void addTerm(String content,String path) {
        File file = new File(path);
        if (file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                LOGGER.error("",e);
            }
        }
        BufferedWriter bw = null;
        BufferedReader br = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            if(br.readLine() != null) { //这里判断第一次向文件中写数据时不换行
                bw.newLine();
            }
            bw.append(content);
        } catch (FileNotFoundException e) {
            LOGGER.error("",e);
        } catch(IOException e) {
            LOGGER.error("",e);
        } finally {
            try {
                if(bw != null)
                    bw.close();
            } catch (IOException e) {
                LOGGER.error("",e);
            }
        }
    }
}
